<template>
  <div class="schedule">
    <div class="content">
      <div class="content-top">
        <div class="content-title">{{ rowdata.projectName }}</div>
      </div>
      <div class="content-bottom">
        <div class="item">
          <div class="title">立项时间：</div>
          <div class="text">{{ rowdata.createTime }}</div>
        </div>
        <div class="item">
          <div class="title">项目状态：</div>
          <div class="text" style="color: #72b0f5">
            {{ rowdata.projectStatusName }}
          </div>
        </div>
      </div>
    </div>
    <div
      class="tooltip"
      v-if="[1, 3, 5, 6, 7].includes(projectForm.projectStatus)"
    >
      <img src="/src/assets/images/Lament.png" alt="" style="width: 20px" />
      <div class="text">
        {{ rowdata.projectStatusRemark }}
      </div>
    </div>
    <div class="form">
      <div class="form-left">
        <div class="item"></div>
        <div
          class="item"
          :class="activeindex == index ? 'activeitem' : ''"
          v-for="(item, index) in taskList"
          :key="index"
          @click="handlerBusSchedule(item, index)"
        >
          {{ item.label }} ({{
            item.type}})
        </div>
      </div>
      <div class="form-right">
        <div class="right-title">{{ presentBusinessScheduleName }}</div>
        <div class="right-form">
          <el-form
            :model="formdata"
            ref="formdataRef"
            :rules="formdataqueryRules"
            label-width="120px"
            class="right-form"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item
                  label="计划开始时间："
                  label-width="120"
                  prop="startTime"
                >
                  <el-date-picker
                    value-format="YYYY-MM-DD HH:mm:ss"
                    v-model="formdata.startTime"
                    class="search-input"
                    type="datetime"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="计划结束时间："
                  label-width="120"
                  prop="endTime"
                >
                  <el-date-picker
                    value-format="YYYY-MM-DD HH:mm:ss"
                    v-model="formdata.endTime"
                    class="search-input"
                    type="datetime"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="项目经理：" prop="allotRelList">
                  <el-select
                    filterable
                    style="width: 100%"
                    v-model="formdata.allotRelList"
                    multiple
                    placeholder="请选择"
                    clearable
                    class="search-input"
                  >
                    <el-option key="0" label="" value="" disabled>
                      <span style="float: left; color: #8492a6">人员姓名</span>
                      <span style="margin: 0 80px 0 50px; color: #8492a6"
                        >联系方式</span
                      >
                      <span
                        style="
                          margin: 0 100px 0 0px;
                          color: #8492a6;
                          font-size: 13px;
                        "
                        >职位</span
                      >
                      <span style="color: #8492a6; font-size: 13px">部门</span>
                    </el-option>
                    <el-option
                      v-for="item in userList"
                      :key="item.userId"
                      :label="item.nickName"
                      :value="item.userId"
                    >
                      <span
                        style="display: inline-block; width: 80px; float: left"
                        >{{ item.nickName }}</span
                      >
                      <span
                        style="
                          display: inline-block;
                          width: 125px;
                          margin: 0 15px 0 23px;
                          color: #8492a6;
                          white-space: nowrap;
                          overflow: hidden;
                          text-overflow: ellipsis;
                        "
                        >{{ item.phonenumber ? item.phonenumber : "--" }}</span
                      >
                      <span
                        style="
                          display: inline-block;
                          width: 125px;
                          font-size: 13px;
                          margin: 0 0px 0 0px;
                          transform: translateY(-11px);
                          color: #8492a6;
                        "
                      >
                        {{ item.postName ? item.postName : "--" }}
                      </span>
                      <span
                        style="
                          display: inline-block;
                          margin: 0 0px 0 0px;
                          font-size: 13px;
                          transform: translateY(-11px);
                          color: #8492a6;
                        "
                      >
                        {{ item.fullDeptName ? item.fullDeptName : "--" }}
                      </span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item
                  label="任务内容："
                  label-width="120"
                  prop="remark"
                >
                  <el-input
                    v-model="formdata.remark"
                    type="textarea"
                    :rows="5"
                    maxlength="500"
                    placeholder="请填写"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import Upload from "@/components/Upload/index";
import { getDictsApi } from "@/api/dict";
import { getallMaterialListApi } from "@/api/information/material";
import {
  getBusScheduleListByProjectId,
  addbusSchedule,
  editbusSchedule,
} from "@/api/sales/marketing.js";
import { getUserListApi } from "@/api/operation/work";
import {
  projectAllotTaskApi,
  projectEditAllotTaskApi,
  projectTaskDetailApi,
  
} from "@/api/operation/project";
import { ElMessage, ElMessageBox } from "element-plus";

const props = defineProps({
  // 操作类型
  rowdata: {
    type: Object,
    default: {},
  },
});

const emit = defineEmits(["getBusScheduleList", "refreshList"]);

console.log("props.rowdata", props.rowdata);

// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);

// 校验规则
const queryRules = {
  includeContract: [
    { required: true, message: "请选择合同签订状态", trigger: "change" },
  ],
  content: [{ required: true, message: "请输入跟进内容", trigger: "blur" }],
  // nextFollowTime: [
  //   { required: true, message: "请选择下次跟进", trigger: "change" },
  // ],
};

let scheduleForm = ref({
  contractTemplate: [],
  projectPracticeInfoRespVos: [],
});

let pagestatus = ref("add");

let statusList = ref([]);
let userList = ref([]);
// 联系人操作类型
const operateType = ref("");
// 新增编辑弹窗显隐
const operateDialogShow = ref(false);
//甲方联系人表单
let contactForm = ref({});

// 销售项目类目列表
const saleCategoryList = ref([]);
// 设备列表
const deviceList = ref([]);

// 销售表单引用
const saleFormRef = ref();
// 联系人表单引用
const contactFormRef = ref();
// 进度表单引用
const scheduleFormRef = ref(null);
//完成表单引用
const formdataRef = ref(null);
// 联系人当前索引(编辑联系人使用)
const tableIndex = ref(null);
// 销售清单当前索引(编辑销售清单使用)
const tableIndexSec = ref(null);
// 联系人表单校验规则
let queryContactRules = {
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 1, max: 15, message: "最多可输入15字", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入联系方式", trigger: "blur" },
    { min: 1, max: 11, message: "最多可输入11字", trigger: "blur" },
  ],
};
// 新增销售列表表单显隐
const saleAddShow = ref(false);
//销售清单
let projectForm = ref({
  projectSaleInfoRespVos: [],
  projectPracticeInfoRespVos: [],
});

// 销售清单表单
let saleForm = ref({
  brand: "",
  saleName: "",
  materialId: null,
  materialUnit: null,
  materialUnitName: "",
  platformName: "",
  technologyParameter: "",
  projectId: null,
  projectSaleId: null,
  quantity: null,
  remarks: "",
  saleCategory: null,
  saleCategoryName: "",
});

let BusScheduleList = reactive([
  {
    name: "项目启动会",
    businessSchedule: 1,
    type:'未分配'
  },
  {
    name: "现场勘察",
    businessSchedule: 2,type:'未分配'
  },
  {
    name: "制定方案",
    businessSchedule: 3,type:'未分配'
  },
  {
    name: "设备出库",
    businessSchedule: 4,type:'未分配'
  },
  {
    name: "安装/调试",
    businessSchedule: 5,type:'未分配'
  },
  {
    name: "飞行验收",
    businessSchedule: 6,type:'未分配'
  },
  {
    name: "安装交付",
    businessSchedule: 7,type:'未分配'
  },
  {
    name: "设备拆装",
    businessSchedule: 8,type:'未分配'
  },
]);

let taskList = ref([])

//左侧表单数据
let formdata = ref({
  allotRelList: [], // 执行人
  deptId: null, //部门id
  endTime: "", // 	计划结束时间
  estimatedWorkHours: null, // 预估工时
  projectId: null, // 项目id
  remark: "", // 备注
  startTime: "", // 	计划开始时间
  taskType: null, // 	任务类型
  tableData: [],
  projectTaskId:null
});

// 项目下任务列表
const projectTaskList = ref([]);

// 销售清单表单校验规则
let formdataqueryRules = {
  estimatedWorkHours: [
      { required: true, message: "请输入预估工时", trigger: "blur" },
    ],
    deptId: [{ required: true, message: "请选择部门", trigger: "change" }],
    allotRelList: [
      { required: true, message: "请选择工程师", trigger: "change" },
    ],
    startTime: [
      { required: true, message: "请选择计划开始时间", trigger: "change" },
    ],
    endTime: [
      { required: true, message: "请选择计划结束时间", trigger: "change" },
    ],
};

let activeindex = ref(0);

let presentBusinessScheduleName = ref("");
let presentBusinessSchedule = ref(null);

/**
 * @description: 任务分配详情
 */
const getBusScheduleList = async () => {

  try {
    await getDictsApi("erp_task_type").then((res) => {
    // 任务列表
    if (res.code === 200) {
      taskList.value = res.data;
      taskList.value.forEach((item) => {
        item.type = "未分配";
      });
    }
  });
  
 
    // formdata.value.projectId = props.rowdata.projectId;
    const res = await projectTaskDetailApi(props.rowdata.projectId);
    console.log('任务分配')
    console.log(res)
    console.log(taskList.value)
    formdata.value.projectId = props.rowdata.projectId;

    projectTaskList.value = res.projectAllotTaskInfoRespVos;

    taskList.value.forEach((item) => {
      projectTaskList.value.forEach((proItem) => {
        if (item.value === proItem.taskType) {
          item.type = "已分配";
        }
      });
    });
    handlerBusSchedule(taskList.value[0],0);
  } catch (error) {}
};
/**
 * @description: 项目进度点击事件
 */
const handlerBusSchedule = async (item, index) => {
  activeindex.value = index;
  formdata.value.allotRelList = [];
  formdata.value.startTime = "";
  formdata.value.endTime = "";
  formdata.value.projectTaskId = null;
  formdata.value.remark = "";
  formdata.value.estimatedWorkHours = "";
  formdata.value.deptId = null;
  // currentTask.value = item.value;
  formdata.value.taskType = item.value;
  projectTaskList.value.forEach(async (taskItem) => {
    // 匹配当前任务
    if (taskItem.taskType === item.value) {
      
      formdata.value.allotRelList = taskItem.executorNums || [];
      formdata.value.startTime = taskItem.startTime;
      formdata.value.endTime = taskItem.endTime;
      formdata.value.projectTaskId = taskItem.projectTaskId;
      formdata.value.remark = taskItem.remark;
      formdata.value.estimatedWorkHours = taskItem.estimatedWorkHours;
      formdata.value.deptId = taskItem.deptId;

      if (props.pageType === "detail") {
        const res = await taskChangeDetailApi(taskItem.projectTaskId);
        changeRecordList.value = res;
      }
    }
  });
};

/**
 * @description: 处理联系人表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleOperate = (type, row, tabIndex) => {
  if (type === "edit") {
    tableIndex.value = tabIndex;
    contactForm.value = JSON.parse(JSON.stringify(row));
    // contactAddShow.value = true;
    operateDialogShow.value = true;
    operateType.value = "edit";
    nextTick(() => {
      contactRefInput.value.focus(); // 聚焦
    });
  } else {
    projectForm.value.projectPracticeInfoRespVos.splice(tabIndex, 1);
  }
};

/**
 * @description: 处理进度填报
 */
const handleraddbusSchedule = async () => {
  if (!formdataRef.value) return;
  await formdataRef.value.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          let res;
          if (formdata.value.projectTaskId) {
            res = await projectEditAllotTaskApi(formdata.value);
          } else {
            res = await projectAllotTaskApi(formdata.value);
          }
          if (res.code === 200) {
            // ElMessage.success(res.msg);
            // formdata.value = JSON.parse(JSON.stringify(formdataTemplate));
            // const result = await projectTaskDetailApi(
            //   formdata.value.projectId
            // );
            // projectTaskList.value = result;
            // taskList.value.forEach((item) => {
            //   projectTaskList.value.forEach((proItem) => {
            //     if (item.value === proItem.taskType) {
            //       item.type = "已分配";
            //     }
            //   });
            // });

            ElMessage.success(res.msg);
          emit("update:followAddShow", false);
          emit("getBusScheduleList");
          emit("refreshList", props.rowdata);
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  await getDictsApi("erp_include_contract").then((res) => {
    // 审核状态
    if (res.code === 200) {
      statusList.value = res.data;
    }
  });
  
  // 销售项目类目
  await getDictsApi("erp_sale_category").then((res) => {
    if (res.code === 200) {
      saleCategoryList.value = res.data;
    }
  });
  // 设备列表
  await getallMaterialListApi({}, {}).then((res) => {
    deviceList.value = res;
  });
}

/**
 * @description: 获取用户列表
 */
const getUserList = async (id) => {
  await getUserListApi(2).then((res) => {
    if (res) {
      userList.value = res;
    }
  });
};

onMounted(() => {
  getUserList();
  getBusScheduleList();
  getDicts();
});

defineExpose({
  handleraddbusSchedule,
});
</script>

<style scoped lang="scss">
.schedule {
  // height: 700px;
  overflow-y: scroll;
  .content {
    background: #ffffff;
    margin-bottom: 20px;
    .content-top {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      .content-title {
        font-family: PingFang SC;
        font-weight: 600;
        font-size: 18px;
        color: #333333;
        line-height: 42px;
      }
    }
    .content-bottom {
      display: flex;
      font-family: PingFang SC;
      font-weight: 400;
      font-size: 14px;
      color: #333333;
      .item {
        width: 20%;
        display: flex;
        align-items: center;
      }
    }
  }
  .tooltip {
    display: flex;
    align-items: center;
    padding: 20px;
    background-color: rgba(217, 87, 0, 0.1);
    color: rgba(217, 87, 0, 1);
    margin-bottom: 20px;
    .text {
      margin-left: 20px;
    }
  }

  .schedule-form {
    margin: 30px 0;
  }
  .form {
    color: #333333;
    display: flex;
    margin-top: 15px;
    background-color: #fafbff;
    .form-left {
      width: 20%;
      height: 100%;
      .item {
        background-color: #d9dce4;
        height: 50px;
        line-height: 50px;
        text-align: center;
        border: 1px solid #f2f2f2;
        cursor: pointer;
      }
      .item:first-child {
        background-color: unset;
        font-size: 18px;
        font-weight: 700;
      }
      .activeitem {
        background-color: #007cef;
      }
    }
    .form-right {
      width: 85%;
      padding-left: 20px;
      border: 1px solid #f2f2f2;
      padding-right: 20px;

      .right-title {
        height: 50px;
        line-height: 50px;
        font-size: 18px;
        font-weight: 700;
      }
      .subtitle {
        display: flex;
        align-items: center;
        margin: 12px 0;
        .dot {
          width: 13px;
          height: 13px;
          background-color: #0179ed;
          border-radius: 50%;
          margin-right: 10px;
        }
      }
      .right-form {
        /* height: calc(100% - 50px); */
        display: flex;
        flex-direction: column;
        justify-content: space-between;
      }
    }
  }
  .contact-info {
    padding: 20px 0 20px 0;
  }
  .button {
    transform: translateX(1063px);
  }
  .marketbutton {
    transform: translateX(1110px);
  }
}
.schedule::-webkit-scrollbar {
  /* 滚动条样式 */
  display: none;
}
</style>

<style>
.el-popper.search-select-option {
  transform: translateX(-300px);
  .el-popper__arrow {
    left: 350px !important;
  }
}
</style>
